<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="70px"
    >
      <el-row>
        <el-form-item label="病案号" prop="medicareNo">
          <el-input
            v-model="queryParams.medicareNo"
            placeholder="请输入病案号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="患者姓名" prop="patientName">
          <el-input
            v-model="queryParams.patientName"
            placeholder="请输入患者姓名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="住院医师" prop="doctorName">
          <el-input
            v-model="queryParams.doctorName"
            placeholder="请输入临床药师"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="病名" prop="illnessName">
          <el-input
            v-model="queryParams.illnessName"
            placeholder="请输入"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
          <!-- <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['workstation:baseInfo:add']"
              >新增</el-button
            > -->
        </el-form-item>

        <el-col :span="6" v-if="false">
          <el-form-item label="科室/病区" prop="deptId">
            <!-- <el-input
              v-model="queryParams.deptId"
              placeholder="请输入科室/病区"
              clearable
              @keyup.enter.native="handleQuery"
            /> -->
            <treeselect
              style="width: 215px"
              v-model="queryParams.deptId"
              :options="deptOptions"
              :show-count="true"
              placeholder="请选择科室/病区"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="false">
          <!-- <el-form-item label="ID号" prop="patientNo">
            <el-input
              v-model="queryParams.patientNo"
              placeholder="请输入ID号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item> -->
          <el-form-item label="监护分级" prop="guardianLevel">
            <!-- <el-input
              v-model="queryParams.guardianLevel"
              placeholder="请输入监护分级"
              clearable
              @keyup.enter.native="handleQuery"
            /> -->
            <el-select
              v-model="queryParams.guardianLevel"
              placeholder="请输入监护分级"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in guardianLevel"
                :key="index"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-form-item label="住院医师" prop="doctorId">
          <el-input
            v-model="queryParams.doctorId"
            placeholder="请输入临床药师"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
      <el-row>
        <el-col :span="12" v-if="false">
          <el-form-item label="出院日期">
            <el-date-picker
              style="width: 595px !important"
              v-model="time"
              type="daterange"
              range-separator="至"
              start-placeholder="请选择出院时间起始日期"
              end-placeholder="请选择出院时间结束日期"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              @change="handletime"
              clearable
            >
            </el-date-picker>
            <!-- <el-date-picker
              clearable
              v-model="queryParams.admissionDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择入院时间"
            >
            </el-date-picker> -->
          </el-form-item>
          <!-- <el-form-item label="床号" prop="bedNo">
            <el-input
              v-model="queryParams.bedNo"
              placeholder="请输入床号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item> -->
        </el-col>
        <!-- <el-form-item label="第一诊断" prop="firstDiagnose">
          <el-input
            v-model="queryParams.firstDiagnose"
            placeholder="请输入第一诊断"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <!-- <el-col :span="6">
          <el-form-item label="住院医师" prop="doctorName">
            <el-input
              v-model="queryParams.doctorName"
              placeholder="请输入临床药师"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="6" v-if="false">
          <el-form-item label="住院状态" prop="patientState">
            <!-- <el-input
              v-model="queryParams.patientState"
              placeholder="请输入住院状态"
              clearable
              @keyup.enter.native="handleQuery"
            /> -->
            <el-select
              v-model="queryParams.patientState"
              placeholder="请输入住院状态"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in patientState"
                :key="index"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-form-item label="年龄" prop="patientAge">
          <el-input
            v-model="queryParams.patientAge"
            placeholder="请输入年龄"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="职业" prop="patientProfession">
          <el-input
            v-model="queryParams.patientProfession"
            placeholder="请输入职业"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="民族" prop="nation">
          <el-input
            v-model="queryParams.nation"
            placeholder="请输入民族"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="身高" prop="patientHeight">
          <el-input
            v-model="queryParams.patientHeight"
            placeholder="请输入身高"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="体重" prop="patientWeight">
          <el-input
            v-model="queryParams.patientWeight"
            placeholder="请输入体重"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="BMI" prop="patientBmi">
          <el-input
            v-model="queryParams.patientBmi"
            placeholder="请输入BMI"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="联系方式" prop="phoneNo">
          <el-input
            v-model="queryParams.phoneNo"
            placeholder="请输入联系方式"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="付费方式" prop="payWay">
          <el-input
            v-model="queryParams.payWay"
            placeholder="请输入付费方式"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="数据来源" prop="sourceInfo">
          <el-input
            v-model="queryParams.sourceInfo"
            placeholder="请输入数据来源"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
      </el-row>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['workstation:baseInfo:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['workstation:baseInfo:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['workstation:baseInfo:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['workstation:baseInfo:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->

    <el-table
      v-loading="loading"
      :data="baseInfoList"
      border
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="患者ID" align="center" prop="id" v-if="true" /> -->
      <el-table-column label="病案号" align="center" prop="medicareNo" />
      <el-table-column label="姓名" align="center" prop="patientName" />
      <el-table-column label="性别" align="center" prop="patientSex">
        <template slot-scope="scope">
          <span>{{
            scope.row.patientSex == 1
              ? "男"
              : scope.row.patientSex == 2
              ? "女"
              : "未知"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="patientAge" />
      <!-- <el-table-column label="病名" align="center" prop="illnessName" />
      <el-table-column label="症型" align="center" prop="symptomName" /> -->
      <el-table-column label="住院医师" align="center" prop="doctorName" />
      <!-- <el-table-column label="ID号" align="center" prop="patientNo" />
      <el-table-column label="科室/病区" align="center" prop="deptId" />
      <el-table-column
        label="入院时间"
        align="center"
        prop="admissionDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.admissionDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="监护分级" align="center" prop="guardianLevel" />
      <el-table-column label="住院状态" align="center" prop="patientState" />
      
      <el-table-column label="职业" align="center" prop="patientProfession" />
      <el-table-column label="民族" align="center" prop="nation" />
      <el-table-column label="身高" align="center" prop="patientHeight" />
      <el-table-column label="体重" align="center" prop="patientWeight" />
      <el-table-column label="BMI" align="center" prop="patientBmi" />
      <el-table-column label="联系方式" align="center" prop="phoneNo" />
      <el-table-column label="付费方式" align="center" prop="payWay" />
      <el-table-column label="数据来源" align="center" prop="sourceInfo" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['workstation:baseInfo:edit']"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleLook(scope.row)"
            v-if="scope.row.diagFlag == 0"
            v-hasPermi="['workstation:baseInfo:edit']"
            >病症</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['workstation:baseInfo:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['workstation:baseInfo:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改患者基本信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="85vw" append-to-body>
      <el-form
        v-if="false"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="85px"
        label-position="left"
      >
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名" />
        </el-form-item>
        <!-- <el-form-item label="病案号" prop="medicalRecordNo">
          <el-input v-model="form.medicalRecordNo" placeholder="请输入病案号" />
        </el-form-item> -->
        <el-form-item label="ID号" prop="patientNo">
          <el-input v-model="form.patientNo" placeholder="请输入ID号" />
        </el-form-item>
        <el-form-item label="科室/病区" prop="deptId">
          <!-- <el-input v-model="form.deptId" placeholder="请输入科室/病区" /> -->
          <treeselect
            v-model="form.deptId"
            :options="deptOptions"
            :show-count="true"
            placeholder="请选择科室/病区"
          />
        </el-form-item>
        <el-form-item label="入院时间" prop="admissionTime">
          <el-date-picker
            clearable
            v-model="form.admissionTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择入院时间"
            :picker-options="setDisabled"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="住院医师" prop="doctorId">
          <!-- <el-input v-model="form.doctorId" placeholder="请输入临床药师" @focus="getDoctorList" /> -->
          <el-select
            v-model="form.doctorId"
            placeholder="请选择临床药师"
            clearable
            @change="handleDoctorName"
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in DoctorList"
              :key="index"
              :label="item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="床号" prop="bedNo">
          <el-input v-model="form.bedNo" placeholder="请输入床号" />
        </el-form-item>
        <el-form-item label="第一诊断" prop="firstDiagnose">
          <el-input v-model="form.firstDiagnose" placeholder="请输入第一诊断" />
        </el-form-item>
        <!-- <el-form-item label="监护分级" prop="guardianLevel">
          <el-input v-model="form.guardianLevel" placeholder="请输入监护分级" />
        </el-form-item>
        <el-form-item label="住院状态" prop="patientState">
          <el-input v-model="form.patientState" placeholder="请输入住院状态" />
        </el-form-item>
        <el-form-item label="年龄" prop="patientAge">
          <el-input v-model="form.patientAge" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="职业" prop="patientProfession">
          <el-input v-model="form.patientProfession" placeholder="请输入职业" />
        </el-form-item>
        <el-form-item label="民族" prop="nation">
          <el-input v-model="form.nation" placeholder="请输入民族" />
        </el-form-item>
        <el-form-item label="身高" prop="patientHeight">
          <el-input v-model="form.patientHeight" placeholder="请输入身高" />
        </el-form-item>
        <el-form-item label="体重" prop="patientWeight">
          <el-input v-model="form.patientWeight" placeholder="请输入体重" />
        </el-form-item>
        <el-form-item label="BMI" prop="patientBmi">
          <el-input v-model="form.patientBmi" placeholder="请输入BMI" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phoneNo">
          <el-input v-model="form.phoneNo" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="付费方式" prop="payWay">
          <el-input v-model="form.payWay" placeholder="请输入付费方式" />
        </el-form-item>
        <el-form-item label="数据来源" prop="sourceInfo">
          <el-input v-model="form.sourceInfo" placeholder="请输入数据来源" />
        </el-form-item> -->
      </el-form>
      <div v-loading="yaoLoading">
        <div class="mb5">
          <div class="mb5" style="font-size: 15px">患者病症信息</div>
          <div
            v-for="(value, key, index) in bingzhengList"
            :key="key"
            style="font-size: 16px"
          >
            <div style="display: flex">
              <div>{{ index + 1 }}、</div>
              <div>
                <span>病：</span>
                {{ key }}
                <div style="margin-top: 5px">
                  <span>证：</span>
                  <span v-for="(item, index) in value" :key="index + 'a'">
                    {{ String.fromCharCode(9312 + index) }} {{ item }}</span
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
        <div style="display: flex">
          <div
            style="
              width: 35%;
              border: 1px solid #ccc;
              font-size: 15px;
              padding: 10px 0 0 10px;
              margin-right: 15px;
            "
          >
            <!-- <div class="mb5">中药饮片处方</div> -->
            <template v-if="zhongyaoyinpian && zhongyaoyinpian.length > 0">
              <div v-for="(item, index) in zhongyaoyinpian" :key="index">
                <div
                  class="yaofangitem"
                  style="display: flex; cursor: pointer"
                  @click="changeyaofang(item, index)"
                  :class="{ one: selectedIndex === index }"
                >
                  <!-- <div>{{ index + 1 }}、</div> -->
                  <div>
                    <div>
                      用法：<span style="color: red">{{ item.use[0] }}</span>
                    </div>
                    <div style="white-space: pre-wrap; line-height: 25px">
                      {{ item.showname }}
                    </div>
                  </div>
                </div>
                <el-divider
                  v-if="index !== zhongyaoyinpian.length - 1"
                ></el-divider>
              </div>
            </template>
            <el-empty v-else description="暂无数据" :image-size="50"></el-empty>
          </div>
          <div style="width: 65%">
            <div>
              <el-row :gutter="0" style="text-align: center; width: 100%">
                <el-col :span="7">
                  病名
                  <el-select
                    v-model="dataparams.illnessName"
                    placeholder="请选择病名"
                    clearable
                    @change="handleDoctorName"
                  >
                    <el-option
                      v-for="(item, index) in bingList"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="7">
                  证型
                  <el-select
                    v-model="dataparams.symptomName"
                    placeholder="请选择证型"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) in zhengList"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="7">
                  <el-button type="primary" @click="handleaudit"
                    >审核药方</el-button
                  >
                  <el-button
                    type="warning"
                    icon="el-icon-download"
                    @click="handleExport"
                    >导出</el-button
                  >
                </el-col>
              </el-row>
            </div>
            <div style="font-size: 15px; margin-top: 15px">
              <template v-if="auditList && auditList.length > 0">
                <div
                  class="tuijianchufang"
                  v-for="(item, index) in auditList"
                  :key="index"
                  style="
                    width: 32%;
                    min-height: 434px;
                    display: inline-block;
                    margin: 5px;
                  "
                >
                  <div style="padding: 5px; border: 1px solid #ccc">
                    <div style="text-align: center">
                      推荐处方{{ item.illnessNo }}
                    </div>
                    <div>
                      <div style="text-align: center; margin-top: 5px">
                        (治法：{{ item.therapy }})
                        <span style="margin-left: 5px">{{
                          item.prescriptionName
                        }}</span>
                      </div>
                      <div style="margin: 5px 0; display: flex">
                        <div style="width: 75px">疾病名称：</div>
                        <span>{{
                          item.illnessName ? item.illnessName : "无"
                        }}</span>
                      </div>
                      <div style="margin: 5px 0; display: flex">
                        <div style="width: 75px">症候名称：</div>
                        <span>{{
                          item.symptomName ? item.symptomName : "无"
                        }}</span>
                      </div>
                      <div style="margin: 5px 0; display: flex">
                        <div style="width: 75px">君药：</div>
                        <span>{{
                          item.monarchDrug ? item.monarchDrug : "无"
                        }}</span>
                      </div>
                      <div style="margin: 5px 0; display: flex">
                        <div>症状与体征：</div>
                        <div style="width: 214px">
                          {{ item.symptomAndSign ? item.symptomAndSign : "无" }}
                        </div>
                      </div>
                      <!-- <div style="margin: 5px 0; display: flex">
                      <div style="width: 75px">治法：</div>
                      <span>{{ item.therapy }}</span>
                    </div> -->
                      <!-- <div style="margin: 5px 0; display: flex">
                      <div style="width: 75px">方剂名称：</div>
                      <span>{{ item.prescriptionName }}</span>
                    </div> -->
                      <div style="margin: 5px 0">
                        <div style="margin-bottom: 5px">方剂组成与剂量：</div>
                        <template
                          v-for="(value, key, index) in item.recommendOfRedMap"
                        >
                          <span
                            :key="index"
                            :style="{ color: value === '1' ? 'red' : '' }"
                            style="line-height: 25px"
                          >
                            {{ key }}
                          </span>
                          <br v-if="(index + 1) % 4 === 0" />
                        </template>
                      </div>
                    </div>
                  </div>

                  <div
                    style="
                      border-left: 1px solid #ccc;
                      border-right: 1px solid #ccc;
                      padding: 5px;
                    "
                  >
                    <div style="margin-bottom: 5px">方剂加减:</div>
                    <div
                      v-for="(fang, index) in item.addAndSubtractList"
                      :key="index"
                      style="display: flex"
                    >
                      <div>{{ index + 1 }}、</div>
                      {{ fang }}
                    </div>
                  </div>
                  <div style="padding: 5px; border: 1px solid #ccc">
                    <span>一致率:</span
                    ><span style="color: red">{{ item.concordanceRate }}</span>
                  </div>
                </div>
              </template>
              <el-empty
                style="text-align: center; margin: 0 auto"
                v-else
                description="暂无数据"
                :image-size="50"
              ></el-empty>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <!-- <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        > -->
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="查看病证"
      :visible.sync="bingopen"
      width="800px"
      append-to-body
    >
      <div
        v-for="(value, key, index) in bingzhengList"
        :key="index"
        style="font-size: 16px"
      >
        <div style="display: flex">
          <div>{{ index + 1 }}、</div>
          <div>
            <span>病：</span>
            {{ key }}
            <div style="margin-top: 5px">
              <span>证：</span>
              <span v-for="(item, index) in value" :key="index">
                {{ String.fromCharCode(9312 + index) }} {{ item }}</span
              >
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        > -->
        <el-button @click="() => (bingopen = false)">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  delBaseInfo,
  addBaseInfo,
  updateBaseInfo,
} from "@/api/workstation/baseInfo";
import { listUser, deptTreeSelect, deptList } from "@/api/system/user";
import {
  tcmPrescription,
  levellist,
  medicalRecordNoname,
  traditional,
  audit,
  exportyaofang,
} from "@/api/workstation/check";
import { getDicts } from "@/api/system/dict/data";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "BaseInfo",
  components: { Treeselect },
  data() {
    return {
      setDisabled: {
        // 返回禁用时间
        disabledDate(time) {
          return time.getTime() > Date.now(); // 可选历史天、可选当前天、不可选未来天
          // return time.getTime() > Date.now() - 8.64e7;  // 可选历史天、不可选当前天、不可选未来天
          // return time.getTime() < Date.now() - 8.64e7;  // 不可选历史天、可选当前天、可选未来天
          // return time.getTime() < Date.now(); // 不可选历史天、不可选当前天、可选未来天
        },
      },
      // 部门树选项
      deptOptions: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 患者基本信息表格数据
      baseInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        doctorName: undefined, // 住院医师的名字  搜索
        medicareNo: undefined,
        patientName: undefined,
        // medicalRecordNo: undefined,
        patientNo: undefined,
        deptId: undefined,
        // admissionDate: undefined,
        admissionTime: undefined,
        doctorId: undefined,
        bedNo: undefined,
        firstDiagnose: undefined,
        guardianLevel: undefined,
        patientState: undefined,
        patientSex: undefined,
        patientAge: undefined,
        patientProfession: undefined,
        nation: undefined,
        patientHeight: undefined,
        patientWeight: undefined,
        patientBmi: undefined,
        phoneNo: undefined,
        payWay: undefined,
        sourceInfo: undefined,
        params: {},
        illnessName: undefined, // 病名
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [{ required: true, message: "患者ID不能为空", trigger: "blur" }],
        patientName: [
          { required: true, message: "患者姓名不能为空", trigger: "blur" },
        ],
        medicalRecordNo: [
          { required: true, message: "病案号不能为空", trigger: "blur" },
        ],
        patientNo: [
          { required: true, message: "ID号不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "科室/病区不能为空", trigger: "blur" },
        ],
        admissionTime: [
          { required: true, message: "入院时间不能为空", trigger: "blur" },
        ],
        doctorId: [
          { required: true, message: "临床药师不能为空", trigger: "blur" },
        ],
        bedNo: [{ required: true, message: "床号不能为空", trigger: "blur" }],
        firstDiagnose: [
          { required: true, message: "第一诊断不能为空", trigger: "blur" },
        ],
        guardianLevel: [
          { required: true, message: "监护分级不能为空", trigger: "blur" },
        ],
        patientState: [
          { required: true, message: "住院状态不能为空", trigger: "blur" },
        ],
        patientSex: [
          { required: true, message: "患者性别不能为空", trigger: "change" },
        ],
        patientAge: [
          { required: true, message: "年龄不能为空", trigger: "blur" },
        ],
        patientProfession: [
          { required: true, message: "职业不能为空", trigger: "blur" },
        ],
        nation: [{ required: true, message: "民族不能为空", trigger: "blur" }],
        patientHeight: [
          { required: true, message: "身高不能为空", trigger: "blur" },
        ],
        patientWeight: [
          { required: true, message: "体重不能为空", trigger: "blur" },
        ],
        patientBmi: [
          { required: true, message: "BMI不能为空", trigger: "blur" },
        ],
        phoneNo: [
          { required: true, message: "联系方式不能为空", trigger: "blur" },
        ],
        payWay: [
          { required: true, message: "付费方式不能为空", trigger: "blur" },
        ],
        sourceInfo: [
          { required: true, message: "数据来源不能为空", trigger: "blur" },
        ],
      },
      guardianLevel: [], // 监护分级
      patientState: [], // 住院状态
      userSex: [], // 患者性别
      payWay: [], // 付费方式
      sourceInfo: [], // 患者信息来源
      bingList: [],
      zhengList: [],
      msg: {}, // 患者管理页搜索条件
      time: "", // 起始日期
      bingopen: false,
      bingList: undefined,
      bing: undefined,
      zheng: undefined,
      zhongyaoyinpian: undefined,
      yaoLoading: false,
      selectedIndex: "",
      dataparams: {
        illnessName: "",
        symptomName: "",
        traditionalNameList: [],
      },
      auditList: [],
      bingzhengList: undefined,
      useInfoData: {}, // 患者当前行信息
    };
  },
  computed: {
    role() {
      return this.$store.state.user.roles;
    },
    useInfo() {
      return this.$store.state.user.user;
    },
    info() {
      return this.$store.state.user.search;
    },
  },
  created() {
    // this.getDeptTree();
    this.getList();
    levellist({
      level: "1",
    }).then((res) => {
      console.log(res);
      this.bingList = res.data;
    });
    // // 查询所有的医生 过滤掉管理员
    // listUser().then((response) => {
    //   // console.log(response.rows);
    //   // console.log(this.role);
    //   if (this.role.length == 1 && this.role[0] == "doctor") {
    //     console.log(this.useInfo);
    //     // this.form.doctorId = this.useInfo.userId
    //     this.DoctorList = [
    //       {
    //         nickName: this.useInfo.userName,
    //         userId: this.useInfo.userId,
    //       },
    //     ];
    //     return;
    //   }
    //   this.DoctorList = response.rows.filter((item) => {
    //     return item.userName !== "admin";
    //   });
    // });
    // // 字典查询  监护分级
    // getDicts("guardian_level").then((res) => {
    //   // console.log(res.data);
    //   this.guardianLevel = res.data;
    // });
    // // 字典查询  住院状态
    // getDicts("patient_state").then((res) => {
    //   // console.log(res.data);
    //   this.patientState = res.data;
    // });
    // // 字典查询  患者性别
    // getDicts("sys_user_sex").then((res) => {
    //   // console.log(res.data);
    //   this.userSex = res.data;
    // });
    // // 字典查询  付费方式
    // getDicts("pay_way").then((res) => {
    //   // console.log(res.data);
    //   this.payWay = res.data;
    // });
    // // 字典查询  患者信息来源
    // getDicts("source_info").then((res) => {
    //   // console.log(res.data);
    //   this.sourceInfo = res.data;
    // });
  },
  methods: {
    // 选择左侧药方
    changeyaofang(item, index) {
      this.selectedIndex = index;
      console.log(item);
      this.dataparams.traditionalNameList = item.name;
      this.dataparams.useNameList = item.showname;
      console.log(this.dataparams);
    },
    // 点击审核按钮
    handleaudit() {
      const { illnessName, symptomName, traditionalNameList } = this.dataparams;
      if (
        illnessName !== "" &&
        symptomName !== "" &&
        traditionalNameList.length !== 0
      ) {
        audit(this.dataparams).then((res) => {
          console.log(res);
          this.auditList = res.data || [];
        });
      } else {
        this.$modal.msg("请同时选择处方、病名、证型后再试！");
      }
    },
    handletime(val) {
      console.log(val);
      if (val) {
        this.queryParams.params = {};
        this.queryParams.params["beginDate"] = val[0];
        this.queryParams.params["endDate"] = val[1];
        console.log(this.queryParams);
      } else {
        this.queryParams.params = {};
      }
    },
    // 去患者详情页
    toUseDetail(item) {
      this.$store.commit("SET_SEARCH", this.queryParams);
      // 打开新窗口
      window.open(
        `/detail?id=${item.id}&medicalRecodeNo=${item.medicalRecordNo}`
      );
      // this.$router.push({
      //   path: "/detail",
      //   query: {
      //     id: item.id,
      //     medicalRecodeNo: item.medicalRecordNo,
      //     // info: this.queryParams, // 记录搜索条件
      //   },
      // });
    },
    /** 查询科室下拉树结构 */
    getDeptTree() {
      console.log(this.role, this.useInfo);
      // 质控员 拥有所有科室
      if (this.role.includes("quality")) {
        deptTreeSelect().then((response) => {
          this.deptOptions = response.data;
        });
        return;
      }
      console.log("用户信息", this.useInfo);
      // 指定了常驻病区 下拉查询
      if (this.useInfo.longDept) {
        let params = {};
        params.params = {};
        params.params["longDept"] = this.useInfo.longDept;
        deptList(params).then((response) => {
          // this.deptOptions = response.data;
          let arr = [];
          response?.data.forEach((item) => {
            let obj = {
              id: item.deptId,
              label: item.deptName,
              parentId: item.parentId,
            };
            arr.push(obj);
          });
          this.deptOptions = arr;
        });
      } else {
        // 指定了科室  没有指定病区
        let params = {
          parentId: this.useInfo.deptId,
        };
        deptList(params).then((response) => {
          // this.deptOptions = response.data;
          let arr = [];
          response?.data.forEach((item) => {
            let obj = {
              id: item.deptId,
              label: item.deptName,
              parentId: item.parentId,
            };
            arr.push(obj);
          });
          this.deptOptions = arr;
        });
      }
    },
    /** 查询患者基本信息列表 */
    getList() {
      this.loading = true;
      tcmPrescription(this.queryParams).then((response) => {
        this.baseInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.selectedIndex = "";
      this.auditList = [];
      this.zhengList = [];
      this.dataparams = {
        illnessName: "",
        symptomName: "",
        traditionalNameList: [],
      };
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        patientName: undefined,
        medicalRecordNo: undefined,
        patientNo: undefined,
        deptId: undefined,
        admissionDate: undefined,
        doctorId: undefined,
        bedNo: undefined,
        firstDiagnose: undefined,
        guardianLevel: undefined,
        patientState: undefined,
        patientSex: undefined,
        patientAge: undefined,
        patientProfession: undefined,
        nation: undefined,
        patientHeight: undefined,
        patientWeight: undefined,
        patientBmi: undefined,
        phoneNo: undefined,
        payWay: undefined,
        sourceInfo: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        patientName: undefined,
        medicalRecordNo: undefined,
        patientNo: undefined,
        deptId: undefined,
        // admissionDate: undefined,
        admissionTime: undefined,
        doctorId: undefined,
        bedNo: undefined,
        firstDiagnose: undefined,
        guardianLevel: undefined,
        patientState: undefined,
        patientSex: undefined,
        patientAge: undefined,
        patientProfession: undefined,
        nation: undefined,
        patientHeight: undefined,
        patientWeight: undefined,
        patientBmi: undefined,
        phoneNo: undefined,
        payWay: undefined,
        sourceInfo: undefined,
        params: {},
      };
      this.time = "";
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加患者基本信息";
    },
    handleDoctorName(val) {
      console.log(val);
      if (val) {
        let params2 = {
          level: "2",
          illnessName: val,
        };
        levellist(params2).then((res) => {
          console.log(res);
          this.zhengList = res.data;
        });
      } else {
        this.zhengList = [];
        this.zheng = "";
      }
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.useInfoData = row; // 保存当前行患者信息
      this.title = "查看患者信息";
      this.open = true;
      this.yaoLoading = true;
      this.selectedIndex = ""; // 清空左侧选择的药方
      this.auditList = []; // 清空点击审核后  返回的列表
      this.zhengList = []; // 清空证的下拉选择框
      this.dataparams = {
        illnessName: "",
        symptomName: "",
        traditionalNameList: [],
      }; // 清空上次选择的数据
      try {
        medicalRecordNoname(row.medicalRecordNo, 3).then((res) => {
          console.log(res.data);
          this.bingzhengList = res.data;
          // this.bingopen = true;
        });
        const res = await traditional(row.medicalRecordNo);
        const data = res.data || {};
        const resultList = Object.values(data).map((arr) => {
          console.log(arr);
          return {
            showname: arr
              .map(
                (item) =>
                  item.orderItemDesc + item.doseQty + item.doseUnitCode + "  "
              )
              .reduce((acc, cur, idx) => {
                return acc + (idx % 4 === 0 && idx !== 0 ? "\n" : "") + cur;
              }),
            name: arr.map((item) => item.orderItemDesc),
            use: arr.map(
              (item) =>
                `${item.instrDesc}  ${item.freqCode}  ${item.durationDesc}`
            ),
          };
        });
        console.log(resultList, "中药处方列表");
        this.zhongyaoyinpian = resultList;
      } catch (error) {
        console.error(error);
      } finally {
        this.yaoLoading = false;
      }
    },
    handleLook(row) {
      // console.log(row);
      medicalRecordNoname(row.medicalRecordNo, 3).then((res) => {
        console.log(res.data);
        this.bingzhengList = res.data;
        this.bingopen = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateBaseInfo(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            this.form.sourceInfo = "0"; // 代表是手工录入
            addBaseInfo(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除患者基本信息编号为"' + ids + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delBaseInfo(ids);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.auditList && this.auditList.length > 0) {
        const queryParams = {
          patientName: this.useInfoData.patientName,
          medicalRecordNo: this.useInfoData.medicalRecordNo,
          doctorName: this.useInfoData.doctorName,
          medicareNo: this.useInfoData.medicareNo,
          patientAge: this.useInfoData.patientAge,
          patientSex:
            this.useInfoData.patientSex == 1
              ? "男"
              : this.useInfoData.patientSex == 2
              ? "女"
              : "未知",
          traditionalPrescription: this.dataparams.useNameList,
          selectIllnessName: this.dataparams.illnessName,
          selectIllnessSymptom: this.dataparams.symptomName,
          tcmRecommendPrescriptionBoList: this.auditList,
        };
        (queryParams.tcmDiagInfoBoList = this.convertToTcmDiagInfoBoList(
          this.bingzhengList
        )),
          // console.log("左侧选择", this.dataparams);
          // console.log("病症集合", this.bingzhengList);
          // console.log("患者信息", this.useInfoData);
          // console.log("推荐的处方", this.auditList);
          // console.log(queryParams);
          this.$download.post(
            "/workstation/tcmPrescription/export",
            queryParams,
            `${this.useInfoData.medicalRecordNo}_${
              this.useInfoData.patientName
            }_${new Date().getTime()}.docx`
          );
      } else {
        this.$modal.msg("请同时选择处方、病名、证型并审核药方后再进行导出！");
      }
    },
    // 处理病症的方法
    convertToTcmDiagInfoBoList(data) {
      const tcmDiagInfoBoList = [];
      for (const [illnessName, symptoms] of Object.entries(data)) {
        const tcmDiagInfoBo = {
          illnessName: illnessName,
          illnessSymptom: symptoms.join("、"),
        };
        tcmDiagInfoBoList.push(tcmDiagInfoBo);
      }
      return tcmDiagInfoBoList;
    },
  },
};
</script>
<style scoped lang="scss">
.tuijianchufang:hover {
  // background-color: #e9f4d8;
  background-color: #fef0df !important;
}

.yaofangitem:hover {
  background-color: #e9f4d8;
}

.selected {
  background-color: #e3e3e3;
  /* 设置选中项的背景色 */
}

// 一级护理
.one {
  background-color: #f9d9dd !important;
}

// 二级护理
.two {
  background-color: #fef0df !important;
}

// 出院患者
.useLeaveStatus {
  display: inline-block;
  text-align: center;
  line-height: 36px;
  width: 73px;
  height: 36px;
  background-color: rgba(245, 154, 35, 1);
  font-size: 14px;
  color: #ffffff;
}

::v-deep .el-dialog__body {
  max-height: 750px !important;
  padding: 20px;
  padding-top: 5px !important;
  overflow: auto;
}
</style>
